import streamlit as st
from tools.verification import *
from time import sleep
from tools.DBUtil import DBUtil
import pandas as pd
from tools.encode_data import encrypt_password
from tools.SecureCookieManager import SecureCookieManager

@st.dialog("新增用户")
def create_user():
    username = st.text_input("用户名", key="create_user_name",placeholder="输入中文姓名")
    create_user = st.button("新增",key="create_user_button")
    create_user_message = st.empty()

    if create_user:
        if username:
            if is_valid_user_exist(username):
                create_user_message.error("用户名已存在,无需再添加!")
                return
            # 写入数据库
            DBUtil.uid_db("INSERT INTO user (username) VALUES (%s)",(username,))
            create_user_message.success("新增用户入库成功")
            sleep(1)
            st.rerun()
        else:
            create_user_message.error("请填写完整信息")

@st.dialog("删除用户")
def delete_user():
    user_options = [""]
    if username == "admin":
        user_result = DBUtil.select_all("SELECT username FROM user;")
    else:
        user_result = DBUtil.select_all("select username from user where usergroup = (select usergroup from user where username =%s);",(username,))
    if user_result:
        user_options = user_options + [user['username'] for user in user_result]
    result = st.multiselect("选择用户姓名", user_options, placeholder="")
    delete_user_button = st.button("删除",key="delete_user_button")
    if delete_user_button:
        if result:
            for user in result:
                DBUtil.uid_db("DELETE FROM user WHERE username = %s",(user,))
            st.success("删除用户成功!")
            sleep(1)
            st.rerun()
        else:
            st.warning("请选择用户")

@st.dialog("重置密码")
def reset_password():
    user_options = [""]
    if username == "admin":
        user_result = DBUtil.select_all("SELECT username FROM user WHERE registertime is not null;")
    else:
        user_result = DBUtil.select_all("select username from user where usergroup = (select usergroup from user where username =%s) and registertime is not null;",(username,))
    if user_result:
        user_options = user_options + [user['username'] for user in user_result]
    result = st.selectbox("选择用户姓名", user_options, index=0, key="reset_user_select")
    reset_user_button = st.button("重置",key="reset_user_button")
    if reset_user_button:
        if result:
            # 写入数据库
            password = encrypt_password("111111")
            DBUtil.uid_db("UPDATE user SET passwd = %s WHERE username = %s",(password,result))
            st.success("重置密码成功! 默认密码为: 111111")
            sleep(1)
            st.rerun()
        else:
            st.warning("请选择用户")

@st.dialog("重置用户")
def reset_user():
    user_options = [""]
    if username == "admin":
        user_result = DBUtil.select_all("SELECT username FROM user WHERE registertime is not null;")
    else:
        user_result = DBUtil.select_all("select username from user where usergroup = (select usergroup from user where username =%s) and registertime is not null;",(username,))
    if user_result:
        user_options = user_options + [user['username'] for user in user_result]
    result = st.selectbox("选择用户姓名", user_options, index=0, key="reset_user_select")
    reset_user_button = st.button("重置",key="reset_user_button")
    if reset_user_button:
        if result:
            # 写入数据库
            DBUtil.uid_db("UPDATE user SET passwd = null,usergroup = null,oamail = null,registertime = null  WHERE username = %s",(result,))
            st.success("重置用户成功!")
            sleep(1)
            st.rerun()
        else:
            st.warning("请选择用户")

# ==================================================页面内容控制========================================================
cookie_manager = SecureCookieManager()
username = cookie_manager.get_cookie("username")

st.title("用户信息管理")
col1,col2,col3,col4,col5 = st.columns([1,1,2,2,15])

if col1.button("新增", key="create_user"):
    create_user()  # 调用创建用户函数

if col2.button("删除",key="delete_user"):
    delete_user()  # 调用删除用户函数

if col3.button("重置密码",key="reset_passwd"):
    reset_password()  # 调用修改用户密码函数

if col4.button("重置用户",key="reset_user"):
    reset_user()  # 调用修改用户函数

if username == "admin":
    data = DBUtil.select_all("SELECT * FROM user;")
else:
    data = DBUtil.select_all("select * from user where usergroup = (select usergroup from user where username =%s);",(username,))

if data:
    df = pd.DataFrame(data)
    df.columns = ['序号','用户名','用户密码',"用户组别","用户邮箱","注册时间","最后登录时间"]
    df.set_index('序号', inplace=True)
    st.dataframe(df)  # 显示虚拟机列表
else:
    st.warning("暂无数据")